// @/components/composables/useCategoryUpload.js
import { ref, reactive } from 'vue'
import { router } from '@/router'
import myaxios from '@/auth/auth.service'
import { showToastMessage } from "@/utils/message"
export function useCategoryUpload() {
  const loading = ref(false)
  const formRef = ref(null)

  // 表单数据（仅用于新增）
  const formData = reactive({
    category: {
      name: '',
      description: '',
      address: '',
      construction_age: '',
      construction_type: '',
      layout_orientation: '',
      protection_level: '',
      image: [],
      // 新增字段：建筑类型多选
      construction_type_selected: [], // ['市井戏台', '其他']
      construction_type_other: '',    // 自定义内容
      // 新增字段：保护级别
      protection_level_main: '',      // '国宝单位'
      protection_level_extra: '',     // '第8批全国重点文物保护单位'
    },
  })
  const getRawFile = (fileItem) => {
    if (!fileItem) return null
    // 兼容Vant的file结构
    if (fileItem.file && fileItem.file instanceof File) return fileItem.file
    // 兼容Element的file结构
    if (fileItem.raw && fileItem.raw instanceof File) return fileItem.raw
    // 兼容直接存储的File对象
    if (fileItem instanceof File) return fileItem
    return null
  }
  const goToCategory = () => {
    router.push('/category')
  }

  const goHome = () => {
    router.push('/category')
  }
  const goToUser = () => {
    router.push('/personalinfo')
  }
  // 提交表单（仅处理新增逻辑）
  const onSubmit = async () => {
    try {
      loading.value = true

      const form = new FormData()

      // ========== 1. 普通字段直接添加 ==========
      form.append('name', formData.category.name)
      form.append('description', formData.category.description || '')
      form.append('address', formData.category.address || '')
      form.append('construction_age', formData.category.construction_age || '')
      form.append('layout_orientation', formData.category.layout_orientation || '')

      // ========== 2. 合并建筑类型 ==========
      let constructionTypeParts = [...formData.category.construction_type_selected]
      // 如果选了“其他”，加上自定义内容
      if (constructionTypeParts.includes('其他') && formData.category.construction_type_other) {
        const otherText = `其他:${formData.category.construction_type_other}`
        // 避免重复
        if (!constructionTypeParts.includes(otherText)) {
          // 替换 "其他" 为 "其他:xxx"
          constructionTypeParts = constructionTypeParts.map(item =>
            item === '其他' ? otherText : item
          )
        }
      }
      const finalConstructionType = constructionTypeParts.join(',')
      form.append('construction_type', finalConstructionType)

      // ========== 3. 合并保护级别 ==========
      const { protection_level_main, protection_level_extra } = formData.category
      let finalProtectionLevel = protection_level_main || ''
      if (protection_level_extra) {
        finalProtectionLevel += `, ${protection_level_extra}`
      }
      form.append('protection_level', finalProtectionLevel.trim())

      // ========== 4. 图片上传 ==========
      if (formData.category.image.length > 0) {
        const rawFile = getRawFile(formData.category.image[0])
        if (!rawFile) {
          showToastMessage("warning", "图片格式不正确，无法上传")
          return
        }
        form.append('image', rawFile)
      }

      // ========== 5. 提交 ==========
      await myaxios.createCategory(form)
      showToastMessage("success", "文物主体创建成功")
      router.push('/category')
    } catch (error) {
      console.error('创建文物主体失败:', error)

      // 处理错误信息展示
      let errorMsg = '操作失败，请重试'

      // 检查是否有响应数据
      if (error.response) {
        // 服务器返回了错误响应
        if (error.response.data) {
          // 检查是否是字符串错误信息
          if (typeof error.response.data === 'string') {
            errorMsg = error.response.data
          }
          // 检查是否是包含error字段的对象
          else if (error.response.data.error) {
            errorMsg = error.response.data.error
          }
          // 检查是否是字段验证错误
          else if (typeof error.response.data === 'object') {
            const errorFields = Object.keys(error.response.data)
            if (errorFields.length > 0) {
              // 显示第一个字段的错误信息
              const firstField = errorFields[0]
              const fieldErrors = error.response.data[firstField]
              if (Array.isArray(fieldErrors)) {
                errorMsg = fieldErrors[0]
              } else {
                errorMsg = String(fieldErrors)
              }
            }
          }
        } else {
          errorMsg = `请求失败: ${error.response.status} ${error.response.statusText}`
        }
      }
      // 检查网络错误
      else if (error.request) {
        errorMsg = '网络连接失败，请检查网络后重试'
      }
      // 其他错误
      else {
        errorMsg = error.message || '操作失败，请重试'
      }
      showToastMessage("error", errorMsg)
      // 展示错误信息
    } finally {
      loading.value = false
    }
  }

  // 表单验证失败处理
  const onFailed = (errorFields) => {
    console.error('表单验证失败:', errorFields)
    showToastMessage("error", "表单验证失败,请检查并填写必填字段")
  }
  // 返回上一页
  const onClickLeft = () => {
    router.back()
  }

  // 重置表单
  const handleReset = () => {
    formData.category = {
      name: '',
      description: '',
      address: '',
      construction_age: '',
      layout_orientation: '',
      image: [],
      construction_type_selected: [],
      construction_type_other: '',
      protection_level_main: '',
      protection_level_extra: '',
    }
    formRef.value?.resetFields()
    showToastMessage("success", "表单已重置")
  }
    return {
      loading,
      formRef,
      formData,
      goHome,
      goToCategory,
      goToUser,
      onSubmit,
      onFailed,
      onClickLeft,
      handleReset,
    }
}
